package com.lantu.sys.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lantu.common.utils.JwtUtil;
import com.lantu.sys.entity.User;
import com.lantu.sys.mapper.UserMapper;
import com.lantu.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.lantu.common.utils.AesUtil.encrypt;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mabc
 * @since 2024-06-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtil jwtUtil;
    //实现方法：
    @Override
    public Map<String,Object> login(User user) {
        //制作一个简单的登录逻辑
        //根据用户名和密码做一个查询，
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,user.getUserName())
                .eq(User::getPasswd,encrypt(user.getPasswd()));
        //查看user表中是否有这个注册用户的信息
        User loginUser1 = this.baseMapper.selectOne(wrapper);

        // 结果不为空则需要生成一个token
        if(loginUser1 != null ){
            //暂时用UUID，终极方案是Jwt
//            String key = "user:" + UUID.randomUUID();



            //存入redis
            loginUser1.setPasswd(null);
//            redisTemplate.opsForValue().set(key,loginUser1,30, TimeUnit.MINUTES);
            //创建Jwt
            String token = jwtUtil.createToken(loginUser1);

            //返回数据
            Map<String,Object> data = new HashMap<>();
            data.put("token",token);
            return data;

            //data是一个键值对：token：key
        }

        return null;
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        //根据token获取用户信息，redis
//        Object obj = redisTemplate.opsForValue().get(token);
        User loginUser = null;
        try{
            loginUser = jwtUtil.parseToken(token, User.class);
        } catch (Exception e){
            e.printStackTrace();
        }


        if(loginUser != null){
//            User loginUser = JSON.parseObject(JSON.toJSONString(obj), User.class);
            Map<String,Object> data = new HashMap<>();
            data.put("username",loginUser.getUserName());
            data.put("userId",loginUser.getUserId());

            //角色
            data.put("role",loginUser.getUserRole());
            return data;
        }
        return null;
    }

    @Override
    public void logout(String token) {
//        redisTemplate.delete(token);
    }

}
